import axios from "axios";

// 推流
export function doOfferPush(
  userId: String,
  roomId: String,
  mediaStream: MediaStream
) {
  // 创建RTCPeerConnection
  var pc = new RTCPeerConnection(null); // 音视频通话的核心类
  mediaStream.getTracks().forEach((track) => pc.addTrack(track, mediaStream)); // 把本地流设置给RTCPeerConnection

  // 创建并发送 offer message
  pc.createOffer({
    offerToReceiveAudio: true,
    offerToReceiveVideo: true,
  })
    .then(function (offer) {
      var uri = "/rtc/v1/publish/";
      pc.setLocalDescription(offer)
        .then(function () {
          var data = {
            api: uri,
            tid: userId,
            streamurl: `webrtc://live/livestream/${roomId}`,
            sdp: offer.sdp,
          };
          console.log("offer data: ", data);

          const share_url = `${window.location.protocol}//${window.location.host}/visit?roomid=${roomId}`;
          console.log(`分享地址: ${share_url}`);
          const share_text = `分享地址: <a target="_blank" href="${share_url}">${share_url}</a>`;
          document.getElementById("shareText").innerHTML = share_text;

          axios.post(uri, data).then((response) => {
            console.log("answer data: ", response.data);
            pc.setRemoteDescription({
              type: "answer",
              sdp: response.data.sdp,
            }).then(() => {});
          });
        })
        .catch(function (error) {
          console.error("offer setLocalDescription failed: " + error);
        });
    })
    .catch(function (error) {
      console.error("doOffer failed: " + error);
    });
}
